﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft
{
    using System.IO;
    using Newtonsoft.Json.Linq;
    using Newtonsoft.Json;

    public class LocalJsonConfig : ConfigBase
    {

        private string localfile;
        public LocalJsonConfig(string filename)
        {
            localfile = filename;

        } 
        protected override void OnInit()
        {
            if (File.Exists(this.localfile))
            {
                using (var sr = File.OpenText(this.localfile))
                {
                    base.buffer = JsonConvert.DeserializeObject<Dictionary<string, string>>(sr.ReadToEnd());
                }
            }
            else
            {
                
            }
        }

        protected override void OnLoadValue(string key)
        {
            if (File.Exists(this.localfile))
            {
                using (var sr = File.OpenText(this.localfile))
                {
                    base.buffer = JsonConvert.DeserializeObject<Dictionary<string, string>>(sr.ReadToEnd());
                }
            }
        }

        protected override void OnSaveValue(string key, string value)
        {
            using (var fs = new FileStream(this.localfile, FileMode.Create, FileAccess.Write))
            {
                using (var sw = new StreamWriter(fs, System.Text.Encoding.UTF8))
                {
                    var json = JsonConvert.SerializeObject(base.buffer, Formatting.Indented);
                    sw.Write(json);
                }
            }
        }
    }
}
